#include"common.hpp"

const int default_fd = -1;

class NamedPipe
{
public:
    NamedPipe(const std::string& name, int fd = default_fd)
        :_name(name)
        ,_fd(fd)
    {}
    bool Create()
    {
        int mkfifo_ret = mkfifo(fifo_name.c_str(), mode);
        if(mkfifo_ret == 0)
        {
            std::cout << "fifo success" << std::endl;
        }
        else
        {
            perror("mkfifo");
            return false;
        }
        return true;
    }

    void Close()
    {
        if(_fd == default_fd)
        {
            return;
        }
        close(_fd);
    }

    bool OpenForRead()
    {
        _fd = open(fifo_name.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            perror("open");
            return false;
        }
        return true;
    }

    bool OpenForWrite()
    {
        _fd = open(fifo_name.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            perror("open");
            return false;
        }
        return true;
    }

    bool Read(std::string* out)
    {
        char buff[SIZE] = { 0 };
        int read_ret = read(_fd, buff, sizeof(buff) - 1);
        if(read_ret > 0)
        {
            buff[read_ret] = '\0';
            *out = buff;
        }
        else
        {
            return false;
        }
        return true;
    }

    void Write(std::string& in)
    {
        write(_fd, in.c_str(), in.size());
    }

    void Remove()
    {
        unlink(_name.c_str());
    }

private:
    int _fd;
    std::string _name;
};